 package cn.edu.cxcyzx.controller;

import java.util.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.edu.cxcyzx.conf.Role;
import cn.edu.cxcyzx.entity.AddStuApply;
import cn.edu.cxcyzx.entity.ApplyProject;
import cn.edu.cxcyzx.entity.CheckProject;
import cn.edu.cxcyzx.entity.CheckProjectPOJO;
import cn.edu.cxcyzx.entity.GiteeVO;
import cn.edu.cxcyzx.entity.MiddleCheck;
import cn.edu.cxcyzx.entity.Progress_project;
import cn.edu.cxcyzx.entity.ProjectInfo;
import cn.edu.cxcyzx.entity.ProjectPOJO;
import cn.edu.cxcyzx.entity.RoomPOJO;
import cn.edu.cxcyzx.entity.Student;
import cn.edu.cxcyzx.entity.Task;
import cn.edu.cxcyzx.entity.Teacher;
import cn.edu.cxcyzx.supervisor.ResultDo;
import cn.edu.cxcyzx.supervisor.ServiceFit;
import cn.edu.cxcyzx.util.MsgJSON;
import cn.edu.cxcyzx.util.Room_useInfo;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Resource
	ServiceFit serviceFit;
	Role r=Role.ADMIN;
	
	@RequestMapping("home")
	public ModelAndView HomePage(HttpSession session){
		System.out.println("首页");
		ModelAndView modelAndView =new ModelAndView("admin/admin_index");
		int checkNum=serviceFit.getCheckProjectService().getNum_checkPro();//申请验收
		int applyNum=serviceFit.getApplyProjectService().getApplyNum_0();//申报请求
		session.setAttribute("applyNum", applyNum);
		session.setAttribute("checkNum", checkNum);
		return modelAndView;
	}
	/**
	 * 录入学生请求列表
	 * @param pageNum
	 * @param model
	 * @return
	 */
	@RequestMapping("/stuApplyList")
	@ResponseBody
	public MsgJSON addStuApplyList(@RequestParam(required=true,defaultValue="1")Integer pageNum,Model model,@RequestParam(value="stuName",defaultValue="")String stuName){
		
		PageHelper.startPage(pageNum, 3);
		List<AddStuApply> list=null;
		ResultDo<List<AddStuApply>> resultDo=serviceFit.getAddStuApplyService().getAllAddStuApply(stuName);
		if(resultDo.isSuccess()){
			System.out.println("---------ok");
			list=resultDo.getResult();
			PageInfo<AddStuApply> pageInfo=new PageInfo<>(list, 5);
			return MsgJSON.success().add("page", pageInfo);
		}else{
			System.out.println("---------fail");
			return MsgJSON.fail();
		}
	}
	/**
	 * 
	 * @param id
	 * @param state
	 * @return
	 */
	@RequestMapping(value="/updateState",method=RequestMethod.GET)
	@ResponseBody
	public MsgJSON updateState(@RequestParam(value="id")int id,@RequestParam(value="state")int state){
		System.out.println("update_Id:"+id);
		serviceFit.getAddStuApplyService().updateState(id,state);
		return MsgJSON.success();	
	}
	
	/**
	 * 学生信息
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("stuInfo")
	public String stuInfo(Model model,@RequestParam(value="pn",defaultValue="1") Integer pn,@RequestParam(value="stuName",defaultValue="")String stuName){
		System.out.println("查询学生："+stuName);
		List<Student> result=null;
		PageHelper.startPage(pn, 5);
		ResultDo<List<Student>> resultDo=serviceFit.getStudentService().getAllStudent(stuName);
		if(resultDo.isSuccess()){
			result=resultDo.getResult();
			PageInfo<Student> pageInfo=new PageInfo<>(result,5);
			model.addAttribute("page", pageInfo);
		}
		return r.getName()+"/stuInfo";
	}
	/**
	 * 添加学生
	 * @return
	 */
	@RequestMapping("addStu")
	public ModelAndView addStuPage(){
		return new ModelAndView("admin/addStu");
	}
	/**
	 * 插入学生
	 * @param stu
	 * @return
	 */
	@RequestMapping(value="/saveStu",method=RequestMethod.POST)
	@ResponseBody
	public MsgJSON saveStu(Student stu){
		System.out.println(stu.getStuName());
		ResultDo<String> resultDo=serviceFit.getStudentService().insertStu(stu);
		if(resultDo.isSuccess()){
			return MsgJSON.success().add("msg", resultDo.getMessage()).add("stu", stu);
		}else{
			return MsgJSON.fail().add("msg", resultDo.getMessage());
		}
		
	}
	@RequestMapping("addStuInfo")
	public ModelAndView addstu(){
		
		return new ModelAndView("admin/addStuInfo");
	}
	
	@RequestMapping("/teaInfoList")
	@ResponseBody
	public MsgJSON getTeaInfoWithJSON(@RequestParam(required=true,defaultValue="1")Integer pageNum,@RequestParam(required=false,defaultValue="")String teaName){
		
		PageHelper.startPage(pageNum, 5);
		List<Teacher> list=null;
		ResultDo<List<Teacher>> resultDo=serviceFit.getTeacherService().getAllTea(teaName);
		if(resultDo.isSuccess()){
			System.out.println("---------ok");
			list=resultDo.getResult();
			PageInfo<Teacher> pageInfo=new PageInfo<>(list, 5);
			return MsgJSON.success().add("page", pageInfo);
		}else{
			System.out.println("---------fail");
			return MsgJSON.fail();
		}
	}
	
	@RequestMapping("teaInfo")
	public String teacherInfo(){
		return r.getName()+"/teacherInfo";
	}
	/**
	 * 新增教师
	 * @param teacher
	 * @return
	 */
	@RequestMapping(value="/saveTea",method=RequestMethod.POST)
	@ResponseBody
	public MsgJSON saveTeacher(Teacher teacher){
		System.out.println(teacher.getTeaName());
		serviceFit.getTeacherService().insertTea(teacher);
		return MsgJSON.success();
		
	}
	/**
	 * 删除教师
	 * @param teaId
	 * @return
	 */
	@RequestMapping(value="/deleteTea",method=RequestMethod.GET)
	@ResponseBody
	public MsgJSON deleteTeacher(@RequestParam(value="teaId")String teaId){
		System.out.println("delete_teaId:"+teaId);
		serviceFit.getTeacherService().deleteTeaByTeaId(teaId);
		return MsgJSON.success();
		
	}
	@RequestMapping("projectInfo")
	public String projectInfoPage(){
		return r.getName()+"/projectInfo";
	}
	/**
	 * 项目申报信息页面
	 * @return
	 */
	@RequestMapping("applyProject")
	public ModelAndView applyProject(){
		ModelAndView modelAndView=new ModelAndView(r.getName()+"/applyProject");
		ResultDo<List<RoomPOJO>> resultDo=serviceFit.getRoomService().getRooms();
		if(resultDo.isSuccess()){
			modelAndView.addObject("list", resultDo.getResult());
		}
		return modelAndView;
	}
	@RequestMapping(value="/getRooms",method=RequestMethod.GET)
	@ResponseBody
	public MsgJSON getRoomsInfo(){
		ResultDo<List<RoomPOJO>> resultDo=serviceFit.getRoomService().getRooms();
		if(resultDo.isSuccess()){
			return MsgJSON.success().add("rooms", resultDo.getResult());
		}else{
			return MsgJSON.fail();
		}
	}
	/**
	 * 项目申报信息
	 * @param pageNum
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/applyProjectInfo")
	@ResponseBody
	public MsgJSON applyProjectInfo(@RequestParam(required=true,defaultValue="1")Integer pageNum,Model model,HttpSession session){
		
		PageHelper.startPage(pageNum, 5);
		List<ApplyProject> list=null;
		ResultDo<List<ApplyProject>> resultDo=serviceFit.getApplyProjectService().getAllApply();
		if(resultDo.isSuccess()){
			System.out.println("--applyProjectInfo-------ok");
			list=resultDo.getResult();
			PageInfo<ApplyProject> pageInfo=new PageInfo<>(list, 5);
			
			int applyNum=serviceFit.getApplyProjectService().getApplyNum_0();//申报请求
			session.setAttribute("applyNum", applyNum);
			return MsgJSON.success().add("page", pageInfo);
		}else{
			System.out.println("--applyProjectInfo-------fail");
			return MsgJSON.fail();
		}
		
	}
	@RequestMapping(value="/getRoomUseInfo")
	@ResponseBody
	public MsgJSON getRoomUseInfo(){
		
		ResultDo<List<RoomPOJO>> resultDo=serviceFit.getRoomService().getRooms();
		if(resultDo.isSuccess()){
			return MsgJSON.success().add("list", resultDo.getResult());
		}else{
			return MsgJSON.fail();
		}
	}
	/**
	 * 通过申报项目状态
	 * @param projectId
	 * @param status
	 * @return
	 */
	@RequestMapping(value="/sucessProjectStatus")
	@ResponseBody
	public MsgJSON editProjectStatus(@RequestParam(value="projectId",required=true)Integer projectId,@RequestParam(required=false)String roomId){
		ApplyProject project=new ApplyProject();
		project.setProjectId(projectId);
		project.setProjectStatus(1);
		System.out.println("projectId:"+projectId+",roomId:"+roomId);
		
		serviceFit.getApplyProjectService().updateStatus(project,roomId);
		return MsgJSON.success();
		
		
	}
	@RequestMapping(value="/failProjectStatus")
	@ResponseBody
	public MsgJSON failProjectStatus(@RequestParam(value="projectId",required=true)Integer projectId,String fail_reason){
		ApplyProject project=new ApplyProject();
		project.setProjectId(projectId);
		project.setProjectStatus(2);
		project.setFail_reason(fail_reason);
		System.out.println("projectId:"+projectId+",fail_reason:"+fail_reason);
		serviceFit.getApplyProjectService().updateStatus(project,null);
		return MsgJSON.success();
	}
	/**
	 * 项目信息
	 * @param pageNum
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getProjectInfo")
	@ResponseBody
	public MsgJSON getProjectInfo(@RequestParam(required=true,defaultValue="1")Integer pageNum,Model model){
		PageHelper.startPage(pageNum, 2);
		List<ProjectInfo> list=null;
		ResultDo<List<ProjectInfo>> resultDo=serviceFit.getProjectService().getAllPro();
		if(resultDo.isSuccess()){
			
			list=resultDo.getResult();
			System.out.println("--getProjectInfo-------ok:"+list.size());
			PageInfo<ProjectInfo> pageInfo=new PageInfo<>(list, 2);
			return MsgJSON.success().add("page", pageInfo);
		}else{
			System.out.println("--getProjectInfo-------fail");
			return MsgJSON.fail();
		}
	}
	/**
	 * 项目——进度控制——页面
	 */
	@RequestMapping("progressControl")
	public ModelAndView progressControl(HttpSession session,@RequestParam(required=true,defaultValue="1")Integer pageNum){
		ModelAndView modelAndView=new ModelAndView("admin/progressControl");
		PageHelper.startPage(pageNum,1);
		ResultDo<List<ProjectInfo>> resultDo=serviceFit.getProjectService().getProgressPro();
		if(resultDo.isSuccess()){
			System.out.println(resultDo.getResult().toString());
			PageInfo<ProjectInfo> pageInfo=new PageInfo<>(resultDo.getResult(),1);
			modelAndView.addObject("pageInfo",pageInfo);
			System.out.println("pageNum:"+pageNum);
			System.out.println("项目信息:"+pageInfo.getList().get(0).toString());
			
			int projectId=resultDo.getResult().get(0).getProject().getProjectId();
			ResultDo<MiddleCheck> resultDo2=serviceFit.getMiddleCheckService().getMiddleCheck(projectId);
			if(resultDo2.isSuccess()){
				System.out.println("middleCheck:"+resultDo2.getResult().toString());
				modelAndView.addObject("middleCheck", resultDo2.getResult());
			}
			Date lastDate=serviceFit.getRoom_useService().getMaxDate(projectId);
			System.out.println("lastDate:"+lastDate);
			modelAndView.addObject("last_date", lastDate);
		}else{
			modelAndView.addObject("errorMsg", "未查到任务信息！");
		}
		return modelAndView;
	}
	/**
	 * 跳往gitPutInfo.jsp
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value="/gitPutInfo")
	public ModelAndView gitPutInfo(String projectId){
		ModelAndView modelAndView=new ModelAndView("admin/gitPutInfo");
		modelAndView.addObject("projectId", projectId);
		return modelAndView;
	}
	/**
	 * 中期检查
	 * @param middleCheck
	 * @return
	 */
	@RequestMapping(value="/setMiddle_check")
	@ResponseBody
	public MsgJSON middle_check(MiddleCheck middleCheck){
		if(middleCheck!=null){
			middleCheck.setCheck_require(middleCheck.getCheck_require().trim());
			System.out.println(middleCheck.toString());
			serviceFit.getMiddleCheckService().insertOne(middleCheck);
			return MsgJSON.success();
		}else{
			return MsgJSON.fail();
		}
		
	}
	/**
	 * 设置中期检查结果
	 * @param projectId
	 * @param status
	 * @return
	 */
	@RequestMapping(value="/update_middleCheck")
	@ResponseBody
	public MsgJSON update_middleCheck(Integer projectId,int status){
		serviceFit.getMiddleCheckService().update_middleCheck(projectId, status);
		return MsgJSON.success();
	}
	/**
	 * 项目进度表信息
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value="/getProject_map")
	@ResponseBody
	public MsgJSON pro_projectInfo(@RequestParam(required=true,value="projectId")String projectId){
		
		ResultDo<List<Progress_project>> resultDo=serviceFit.getProject_progressService().getProgress(Integer.parseInt(projectId));
		if(resultDo.isSuccess()){
			List<Progress_project> list=resultDo.getResult();
			System.out.println("size:"+list.size());
			String[] categories=new String[list.size()];
			double[] data=new double[list.size()];
			String[] desc=new String[list.size()];
			Iterator<Progress_project> iterator=list.iterator();
			int i=0;
			while(iterator.hasNext()){
				Progress_project pro=iterator.next();
				StringBuilder des=new StringBuilder("");
				if(pro.getDescribe()!=null&&!"".equals(pro.getDescribe())){
					des.append(pro.getDescribe()+"·");
				}
				des.append((new SimpleDateFormat("yyyy-MM-dd").format(pro.getTime())).toString());
				categories[i]=des.toString();
				System.out.println(des.toString());
				data[i]=pro.getProgress();
				desc[i]=pro.getDescribe();
				i++;
			}
			
			return MsgJSON.success().add("categories", categories).add("data", data).add("desc", desc);
		}else{
			return MsgJSON.fail().add("errorMsg", "数据获取失败");
		}
		
	}
	/**
	 * 任务进度表
	 * @param projectId
	 * @return
	 */
	@RequestMapping(value="/getTasks_map")
	@ResponseBody
	public MsgJSON pro_taskInfo(@RequestParam(required=true,value="projectId")String projectId){
		ResultDo<List<Task>> resultDo=serviceFit.getTaskService().getTasks(Integer.parseInt(projectId));
		if(resultDo.isSuccess()){
			List<Task> list=resultDo.getResult();
			System.out.println(list.size());
			String[] categories=new String[list.size()];
			int[] data=new int[list.size()];
			Iterator<Task> iterator=list.iterator();
			int i=0;
			while(iterator.hasNext()){
				Task task=iterator.next();
				categories[i]=task.getTaskName();
				data[i]=task.getProcess();
				i++;
			}
			
			return MsgJSON.success().add("categories", categories).add("data", data);
		}else{
			return MsgJSON.fail().add("errorMsg", "数据获取失败");
		}
		
	}
	/**
	 * 根据时间查询房屋使用情况
	 * @param projectId
	 * @param date
	 * @return
	 */
	@RequestMapping(value="/getRoomUse_day")
	@ResponseBody
	public MsgJSON pro_roomUse_day(@RequestParam(required=true,value="projectId")String projectId,@RequestParam(required=false)String date){
		Date select_date;
		if(date==null||"".equals(date)){
			select_date=serviceFit.getRoom_useService().getMaxDate(Integer.parseInt(projectId));

		}else{
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
			try {
				
				select_date=new Date(format.parse(date).getTime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return MsgJSON.fail();
			}
		}
		ResultDo<int[]> resultDo=serviceFit.getRoom_useService().getNum_proANDdate(Integer.parseInt(projectId), select_date);
		if(resultDo.isSuccess()){
			System.out.println("nums:"+Arrays.toString(resultDo.getResult()));
			return MsgJSON.success().add("nums", resultDo.getResult());
		}else{
			return MsgJSON.fail();
		}
		
	}
	/**
	 * 下拉框查询房屋使用情况
	 * @param state
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/getRoomUse_range")
	@ResponseBody
	public MsgJSON getRoomUse_range(@RequestParam(defaultValue="0")String state,@RequestParam(required=true)int projectId){
		int status=Integer.parseInt(state);
		ResultDo<List<Room_useInfo>> resultDo=serviceFit.getRoom_useService().getRoom_useInfo(projectId, status);
		if(resultDo.isSuccess()){
			return MsgJSON.success().add("list", resultDo.getResult());
		}else{
			return MsgJSON.fail();
		}
		
	}
	
	/**
	 * 延期请求页面
	 * @return
	 */
	@RequestMapping("/delayPro")
	public ModelAndView delayPro_page() {
		List<ProjectPOJO> list=serviceFit.getProjectService().getDalayPro();
		System.out.println(list.toArray().toString());
		ModelAndView modelAndView=new ModelAndView(r.getName()+"/delayPro");
		modelAndView.addObject("list", list);
		return modelAndView;
		
	}
	/**
	 * 验收请求页面
	 * @return
	 */
	@RequestMapping("/checkPro")
	public ModelAndView checkPro_page(){
		List<CheckProjectPOJO> list=serviceFit.getCheckProjectService().getAllPro();
		System.out.println(list.get(0).getProjectName()+":"+list.get(0).getSubmit_time());
		System.out.println(list.get(0).getProjectName()+":"+list.get(0).getSubmit_time().toString());
		ModelAndView modelAndView=new ModelAndView(r.getName()+"/checkPro");
		modelAndView.addObject("list", list);
		return modelAndView;
		
	}
	/**
	 * 同意验收申请
	 * @return
	 */
	@RequestMapping("/success_checkPro")
	@ResponseBody
	public MsgJSON success_checkPro(int projectId,Timestamp checkTime,String checkAddress,String check_claim){
		CheckProject checkProject=new CheckProject(projectId, checkTime, checkAddress, check_claim);
		System.out.println("success_checkPro:"+checkProject.toString());
		if(checkProject!=null&&checkProject.getProjectId()>0){
			serviceFit.getCheckProjectService().success_checkPro(checkProject);
			return MsgJSON.success();
		}else{
			return MsgJSON.fail().add("errorMsg", "数据出错");
		}
		
		
	}
	/**
	 * 驳回验收申请
	 * @return
	 */
	@RequestMapping("/fail_checkPro")
	@ResponseBody
	public MsgJSON fail_checkPro(@RequestParam(value="failCheckInfo")String failCheckInfo,@RequestParam(value="projectId")String projectId_str){
		System.out.println("failCheckInfo:"+failCheckInfo+",projectId:"+projectId_str);
		int projectId=Integer.parseInt(projectId_str);
		if(projectId>0&&!"".equals(failCheckInfo)){
			serviceFit.getCheckProjectService().fail_checkPro(failCheckInfo, projectId);
			return MsgJSON.success();
		}else{
			return MsgJSON.fail().add("errorMsg", "数据有误！");
		}
		
		
	}
	/**
	 * 设置验收结果
	 * @param projectId
	 * @param pro_rate
	 * @param pro_comment
	 * @param rebackRoom
	 * @return
	 */
	@RequestMapping("/checkResult")
	@ResponseBody
	public MsgJSON setCheckResult(@RequestParam(value="projectId")String projectId,String pro_rate,String pro_comment,int rebackRoom){
		System.out.println("proId:"+projectId+",proRate:"+pro_rate+",pro_comment:"+pro_comment);
		int proId=Integer.parseInt(projectId);
		float proRate=Float.parseFloat(pro_rate);
		System.out.println("proId:"+proId+",proRate:"+proRate+",pro_comment:"+pro_comment);
		CheckProject checkProject=new CheckProject(proId,proRate, pro_comment,rebackRoom);
		serviceFit.getCheckProjectService().setCheckResult(checkProject);
		return MsgJSON.success();
		
	}
	/**
	 * gitee信息页面
	 * @return
	 */
	@RequestMapping("giteeInfo")
	public String giteePage(){
		return "admin/GiteeInfo";
	}
	/**
	 * 查询所有的gitee信息
	 * @return
	 */
	@RequestMapping("/getGiteeInfo")
	@ResponseBody
	public MsgJSON getGiteeInfo(){
		ResultDo<List<GiteeVO>> resultDo=serviceFit.getGiteeService().getAll();
		if(resultDo.isSuccess()){
			return MsgJSON.success().add("gitees", resultDo.getResult());
		}else{
			return MsgJSON.fail();
		}
	}
	
	/**
	 * 重新登陆
	 * @param session
	 * @return
	 */
	@RequestMapping("/relogin")
	@ResponseBody
	public MsgJSON reLogin(HttpSession session){
		session.removeAttribute("admin");
		return MsgJSON.success();
	}
	
	/**
	 * 退出
	 * @param session
	 * @return
	 */
	@RequestMapping("quit")
	public String quit(HttpSession session){
		session.removeAttribute("admin");
		return "redirect:/login.jsp";
	}
}
